﻿using System.Collections.Generic;
using Enterprise.Framework.Core.Exceptions;
using Enterprise.Framework.DomainModel;
using Enterprise.Framework.DomainModel.Repositories;
using Enterprise.Framework.DomainModel.Specifications;
using Resto.CostControl.Core.Domain.Resource;
using Resto.CostControl.Common.Utility;

namespace Resto.CostControl.Core.Domain.Model
{
    /// <summary>
    /// 品名
    /// </summary>
    public partial class Material : IAggregationRoot
    {
        #region 构造函数

        internal Material() {
            this.ID = IDHelper.CreateNewID();
        }

        #endregion

        #region 私有属性

        private IEntityRepository<Material> _Repository;
        private IEntityRepository<Material> Repository
        {
            get
            {
                if (_Repository == null)
                    _Repository = RestoCostDomainSession.CurrentSession.CreateEntityRepository<Material>();

                return _Repository;
            }
        }

        #endregion

        #region 验证方法

        protected void Validate()
        {
            List<string> messageList = new List<string>();

            ValidateNameRepeat(messageList);
            ValidateCodeRepeat(messageList);

            if (messageList.Count > 0)
                throw new BusinessValidationException(messageList.ToArray());
        }

        private void ValidateNameRepeat(IList<string> messageList)
        {
            ISpecification<Material> spec = Specification<Material>.Create(p => p.Name == this.Name);
            spec = spec.And(Specification<Material>.Create(p => p.ID != ID));

            bool result = Repository.Count(spec) > 0;
            if (result)
                messageList.Add(string.Format(MaterialResource.ValidateException_MaterialName_Repeat, this.Name));
        }

        private void ValidateCodeRepeat(IList<string> messageList)
        {
            ISpecification<Material> spec = Specification<Material>.Create(p => p.Code == this.Code);
            spec = spec.And(Specification<Material>.Create(p => p.ID != ID));

            bool result = Repository.Count(spec) > 0;
            if (result)
                messageList.Add(string.Format(MaterialResource.ValidateException_MaterialCode_Repeat, this.Code));
        }

        #endregion

        #region 公共方法

        internal abstract void Add();

        internal abstract void Update();

        internal abstract void Delete();

        internal virtual void UpdatePrice(decimal price)
        {
   
        }
        
        #endregion
    }
}
